from django import forms

from django.core.validators import RegexValidator

from django_redis import get_redis_connection


from user.models import User
class CheckSmsCode(forms.Form):
    def __init__(self,*args,**kwargs):
        self.request=kwargs.pop("request",None)
        super().__init__(*args,**kwargs)
    regex_mobile=RegexValidator(r'^1[3-9]\d{9}$',"手机号不匹配")

    mobile=forms.CharField(max_length=11,min_length=11,validators=[regex_mobile],
                           error_messages={
                               "max_length":"手机号长度错误",
                               "min_length":"手机号长度错误",
                               "validators":"手机号格式错误",
                               "required":"手机号不能为空",
                           })
    captcha=forms.CharField(max_length=4,min_length=4,
                            error_messages={
                                "max_length": "图片验证码长度错误",
                                "min_length": "图片验证码长度错误",
                                "required": "图片验证码不能为空",
                            })
    def clean(self):
        clean_data=super().clean()
        mobile=clean_data.get("mobile")
        captcha=clean_data.get("captcha")
        if User.objects.filter(mobile=mobile):
            raise forms.ValidationError("手机号已经存在")
        redis_conn=get_redis_connection("smscode")
        sms=redis_conn.get('mobile_flag_{}'.format(mobile))
        if sms:
            raise forms.ValidationError("获取短信验证码过于频繁")
        image_code=self.request.session.get("image_code")
        if not image_code:
            raise forms.ValidationError("图片验证码已过期")
        if captcha.upper() != image_code.upper():
            raise forms.ValidationError("图片验证码错误")





